package com.mou.controller.admin;

import com.mou.annotation.Log;
import com.mou.dto.CategoryDTO;
import com.mou.dto.CategoryPageQueryDTO;
import com.mou.entity.Category;
import com.mou.result.PageResult;
import com.mou.result.Result;
import com.mou.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/admin/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    @PostMapping("/add")
    public Result<String> add(@RequestBody CategoryDTO categoryDTO) {
        log.info("用户新增:{}", categoryDTO);
        if(categoryDTO.getParentId()==null){
            categoryDTO.setParentId(0);
        }
        categoryService.add(categoryDTO);
        return Result.success();
    }


    @GetMapping("/page")
    @ResponseBody
    public Result<PageResult> page(CategoryPageQueryDTO categoryPageQueryDTO) {
        log.info("分类分页查询:{}", categoryPageQueryDTO);
        PageResult pageResult = categoryService.pageQuery(categoryPageQueryDTO);
        return Result.success(pageResult);
    }

    @Log
    @PutMapping("/delete/{ids}")
    public Result<String> deleted(@PathVariable("ids") List<Integer> ids) {
        log.info("分类删除:{}", ids);
        for (Integer id : ids) {
            categoryService.deleted(id);
        }
        return Result.success();
    }

    @Log
    @PutMapping("/update")
    public Result<String> update(@RequestBody CategoryDTO categoryDTO) {
        log.info("用户修改:{}", categoryDTO);
        if(categoryDTO.getParentId()==null){
            categoryDTO.setParentId(0);
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryService.updateById(category);
        return Result.success();
    }
}
